<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC 服务器管理后台</title>
    <!-- Element UI CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- Vue.js -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- Element UI JS -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- Axios for HTTP requests -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
        }
        .login-container {
            min-height: 100vh;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-form {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            width: 400px;
        }
        .admin-container {
            min-height: 100vh;
            background-color: #f5f5f5;
        }
        .header {
            background: #fff;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 0 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .content {
            padding: 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 登录页面 -->
        <div v-if="!isLoggedIn" class="login-container">
            <div class="login-form">
                <h2 style="text-align: center; margin-bottom: 30px; color: #333;">管理员登录</h2>
                <el-form :model="loginForm" :rules="loginRules" ref="loginForm" label-width="80px">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="loginForm.password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="login" :loading="loginLoading" style="width: 100%;">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 管理后台 -->
        <div v-else class="admin-container">
            <!-- 头部 -->
            <div class="header">
                <h2>WebRTC 服务器管理后台</h2>
                <div>
                    <span style="margin-right: 20px;">欢迎，{{ currentUser.username }}</span>
                    <el-button type="danger" size="small" @click="logout">退出登录</el-button>
                    <el-button type="success" size="small" @click="showBroadcastDialog = true">
                        <i class="el-icon-message"></i> 系统广播
                    </el-button>
                    <el-button type="warning" size="small" @click="showLogDialog = true">
                        <i class="el-icon-document"></i> 查看日志
                    </el-button>
                    <el-button type="info" size="small" @click="reconnectSSE" :loading="sseReconnecting">
                        <i class="el-icon-refresh"></i> 重连SSE
                    </el-button>
                </div>
            </div>

            <!-- 主要内容 -->
            <div class="content">
                <!-- 统计卡片 -->
                <el-row :gutter="20" style="margin-bottom: 20px;">
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>在线用户</span>
                            </div>
                            <div style="text-align: center;">
                                <span style="font-size: 32px; color: #409EFF;">{{ stats.onlineUsers }}</span>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>活跃房间</span>
                            </div>
                            <div style="text-align: center;">
                                <span style="font-size: 32px; color: #67C23A;">{{ stats.activeRooms }}</span>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>总连接数</span>
                            </div>
                            <div style="text-align: center;">
                                <span style="font-size: 32px; color: #E6A23C;">{{ stats.totalConnections }}</span>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>服务器状态</span>
                            </div>
                            <div style="text-align: center;">
                                <el-tag :type="stats.serverStatus === 'ok' ? 'success' : 'danger'" size="large">
                                    {{ stats.serverStatus === 'ok' ? '正常' : '异常' }}
                                </el-tag>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>

                <!-- 功能面板 -->
                <el-row :gutter="20">
                    <el-col :span="12" :xs="24" :sm="24" :lg="12">
                        <!-- 房间列表 -->
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>房间列表</span>
                                <!-- <el-tag type="info" size="mini" style="float: right; margin-right: 10px;">
                                    自动更新 (5秒)
                                </el-tag> -->
                            </div>
                            <el-table :data="rooms" :span-method="roomObjectSpanMethod" height="580" style="width: 100%" v-loading="roomsLoading">
                                <el-table-column prop="roomId" label="房间ID" width="120"></el-table-column>
                                <el-table-column prop="deviceId" label="设备ID" width="120"></el-table-column>
                                <el-table-column prop="connId" label="连接ID"></el-table-column>
                                <el-table-column label="是否在线" width="80">
                                    <template slot-scope="scope">
                                        <el-tag :type="scope.row.isOnline ? 'success' : 'danger'" size="mini">
                                            {{ scope.row.isOnline ? '在线' : '离线' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="status" label="状态" width="80">
                                    <template slot-scope="scope">
                                        <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'" size="mini">
                                            {{ scope.row.status === 'active' ? '活跃' : '空闲' }}
                                        </el-tag>
                                        <!-- <el-button size="mini" type="warning" @click="hangupRoom(scope.row)" v-if="scope.row.status === 'active'">结束通话</el-button> -->
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="80">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="danger" @click="kickConnection(scope.row)">踢下线</el-button>
                                        <!-- <el-button size="mini" type="danger" @click="deleteRoom(scope.row)">删除</el-button> -->
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-card>
                    </el-col>
                    <el-col :span="12" :xs="24" :sm="24" :lg="12">
                        <!-- 客户端设备 -->
                        <el-card shadow="hover">
                            <div slot="header">
                                <span>设备管理</span>
                                <el-button type="primary" size="small" @click="showRoomDialog = true" style="float: right; margin-right: 10px;">
                                    <i class="el-icon-plus"></i> 绑定设备
                                </el-button>
                                <!-- <el-tag :type="sseConnected ? 'success' : 'danger'" size="mini" style="float: right; margin-right: 10px;">
                                    {{ sseConnected ? 'SSE已连接' : 'SSE未连接' }}
                                </el-tag> -->
                            </div>
                            <el-table :data="deviceList" :span-method="objectSpanMethod" style="width: 100%" height="580" v-loading="connectionsLoading">
                                <el-table-column prop="roomId" label="房间ID" width="180"></el-table-column>
                                <el-table-column prop="deviceId" label="设备ID"></el-table-column>
                                <el-table-column label="是否在线" width="120">
                                    <template slot-scope="scope">
                                        <el-tag :type="scope.row.isOnline ? 'success' : 'danger'" size="mini">
                                            {{ scope.row.isOnline ? '在线' : '离线' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="150">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="danger" @click="deleteDevice(scope.row)">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
        </div>

        <!-- 广播消息对话框 -->
        <el-dialog title="系统广播" :visible.sync="showBroadcastDialog" width="500px">
            <el-form :model="broadcastForm" label-width="80px">
                <el-form-item label="消息类型">
                    <el-select v-model="broadcastForm.type" placeholder="请选择消息类型">
                        <el-option label="系统通知" value="system"></el-option>
                        <el-option label="维护通知" value="maintenance"></el-option>
                        <el-option label="紧急通知" value="urgent"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="消息内容">
                    <el-input type="textarea" v-model="broadcastForm.message" placeholder="请输入要广播的消息"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showBroadcastDialog = false">取消</el-button>
                <el-button type="primary" @click="sendBroadcast" :loading="broadcastLoading">发送</el-button>
            </div>
        </el-dialog>

        <!-- 创建房间对话框 -->
        <el-dialog title="绑定设备" :visible.sync="showRoomDialog" width="500px">
            <el-form :model="roomForm" label-width="80px">
                <el-form-item label="设备ID">
                    <el-input v-model="roomForm.device_id" placeholder="请输入设备ID"></el-input>
                </el-form-item>
                <el-form-item label="房间ID">
                    <el-input v-model="roomForm.room_id" placeholder="请输入房间ID"></el-input>
                </el-form-item>
                <!-- <el-form-item label="房间描述">
                    <el-input type="textarea" v-model="roomForm.description" placeholder="请输入房间描述"></el-input>
                </el-form-item>
                <el-form-item label="最大人数">
                    <el-input-number v-model="roomForm.maxParticipants" :min="2" :max="100"></el-input-number>
                </el-form-item> -->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="showRoomDialog = false">取消</el-button>
                <el-button type="primary" @click="createRoom" :loading="roomLoading">创建</el-button>
            </div>
        </el-dialog>

        <!-- 日志查看对话框 -->
        <el-dialog title="系统日志" :visible.sync="showLogDialog" width="80%">
            <div style="height: 400px; overflow-y: auto; background: #f8f9fa; padding: 10px; border-radius: 4px;">
                <div v-for="(log, index) in logs" :key="index" style="margin-bottom: 5px; font-family: monospace; font-size: 12px;">
                    <span style="color: #909399;">[{{ log.timestamp }}]</span>
                    <span :style="{ color: log.type === 'error' ? '#F56C6C' : log.type === 'success' ? '#67C23A' : '#606266' }">
                        {{ log.message }}
                    </span>
                </div>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearLogs">清空日志</el-button>
                <el-button type="primary" @click="showLogDialog = false">关闭</el-button>
            </div>
        </el-dialog>
    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    isLoggedIn: false,
                    currentUser: {},
                    loginForm: {
                        username: '',
                        password: ''
                    },
                    loginRules: {
                        username: [
                            { required: true, message: '请输入用户名', trigger: 'blur' }
                        ],
                        password: [
                            { required: true, message: '请输入密码', trigger: 'blur' }
                        ]
                    },
                    loginLoading: false,
                    loading: false,
                    stats: {
                        onlineUsers: 0,
                        activeRooms: 0,
                        totalConnections: 0,
                        serverStatus: 'unknown'
                    },
                    rooms: [],
                    roomSpanArr: [],
                    roomPosition: 0,
                    roomsLoading: false,
                    deviceList: [],
                    spanArr: [], // 二维数组，用于存放单元格合并规则
                    position: 0, // 用于存储相同项的开始index
                    connectionsLoading: false,
                    logs: [],
                    sseConnected: false,
                    sseReconnecting: false,
                    showBroadcastDialog: false,
                    showRoomDialog: false,
                    showLogDialog: false,
                    broadcastForm: {
                        type: 'system',
                        message: ''
                    },
                    roomForm: {
                        device_id: '',
                        room_id: '',
                        maxParticipants: 10
                    },
                    broadcastLoading: false,
                    roomLoading: false
                }
            },
            mounted() {
                this.checkLoginStatus();
                if (this.isLoggedIn) {
                    this.initAdmin();
                }
            },
            beforeDestroy() {
                if (this.eventSource) {
                    this.eventSource.close();
                    this.eventSource = null;
                }
            },
            methods: {
                // 检查登录状态
                checkLoginStatus() {
                    const token = localStorage.getItem('admin_token');
                    const user = localStorage.getItem('admin_user');
                    if (token && user) {
                        this.isLoggedIn = true;
                        this.currentUser = JSON.parse(user);
                    }
                },
                
                // 登录
                async login() {
                    this.$refs.loginForm.validate(async (valid) => {
                        if (valid) {
                            this.loginLoading = true;
                            try {
                                // 这里应该调用实际的登录API
                                // 暂时使用模拟登录
                                if (this.loginForm.username === 'admin' && this.loginForm.password === 'admin123') {
                                    const token = 'mock_token_' + Date.now();
                                    const user = { username: this.loginForm.username, role: 'admin' };
                                    
                                    localStorage.setItem('admin_token', token);
                                    localStorage.setItem('admin_user', JSON.stringify(user));
                                    
                                    this.isLoggedIn = true;
                                    this.currentUser = user;
                                    this.$message.success('登录成功');
                                    this.initAdmin();
                                } else {
                                    this.$message.error('用户名或密码错误');
                                }
                            } catch (error) {
                                this.$message.error('登录失败: ' + error.message);
                            } finally {
                                this.loginLoading = false;
                            }
                        }
                    });
                },
                
                // 退出登录
                logout() {
                    this.$confirm('确定要退出登录吗？', '确认退出', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        localStorage.removeItem('admin_token');
                        localStorage.removeItem('admin_user');
                        this.isLoggedIn = false;
                        this.currentUser = {};
                        this.$message.success('已退出登录');
                    });
                },
                
                // 初始化管理后台
                initAdmin() {
                    this.initSSE();
                    this.addLog('管理后台初始化完成', 'success');
                },
                
                // 初始化SSE连接
                initSSE() {
                    if (this.eventSource) {
                        this.eventSource.close();
                    }
                    
                    this.eventSource = new EventSource('/api/admin/sse');
                    
                    this.eventSource.onopen = () => {
                        this.sseConnected = true;
                        this.addLog('SSE连接已建立', 'success');
                    };
                    
                    this.eventSource.onmessage = (event) => {
                        try {
                            const data = JSON.parse(event.data);
                            this.handleSSEData(data);
                        } catch (e) {
                            this.addLog('SSE消息解析失败: ' + event.data, 'error');
                        }
                    };
                    
                    this.eventSource.onerror = (error) => {
                        this.sseConnected = false;
                        this.addLog('SSE连接错误', 'error');
                        console.error('SSE Error:', error);
                    };
                },
                
                // 重连SSE
                reconnectSSE() {
                    this.sseReconnecting = true;
                    this.addLog('正在重连SSE...', 'info');
                    
                    setTimeout(() => {
                        this.initSSE();
                        this.sseReconnecting = false;
                    }, 1000);
                },
                
                // 处理SSE数据
                handleSSEData(data) {
                    switch (data.type) {
                        case 'connected':
                            this.addLog(`SSE连接建立: ${data.connectionId}`, 'success');
                            break;
                        case 'admin_data':
                            // 更新统计数据
                            this.stats = {
                                onlineUsers: data.metrics.connections,
                                activeRooms: data.metrics.calls,
                                totalConnections: data.metrics.connections,
                                serverStatus: 'ok'
                            };
                            
                            // 更新房间列表
                            this.rooms = data.rooms || []
                            
                            // 更新连接列表
                            this.deviceList = data.deviceList
                            this.rowspan(0, 'roomId')

                            this.addLog('数据已更新', 'info');
                            break;
                        case 'error':
                            this.addLog(`SSE错误: ${data.message}`, 'error');
                            break;
                        default:
                            this.addLog(`收到SSE消息: ${data.type}`, 'info');
                    }
                },
                
                rowspan(idx, prop) {
                    this.spanArr[idx] = []
                    this.position = 0
                    this.deviceList.forEach((item, index) => {
                        if (index === 0) {
                            this.spanArr[idx].push(1)
                            this.position = 0
                        } else {
                            if (this.deviceList[index][prop] === this.deviceList[index - 1][prop]) {
                                this.spanArr[idx][this.position] += 1// 有相同项
                                this.spanArr[idx].push(0) // 名称相同后往数组里面加一项0
                            } else {
                                this.spanArr[idx].push(1)// 同列的前后两行单元格不相同
                                this.position = index
                            }
                        }
                    })

                    this.roomSpanArr[idx] = []
                    this.roomPosition = 0
                    this.rooms.forEach((item, index) => {
                        if (index === 0) {
                            this.roomSpanArr[idx].push(1)
                            this.roomPosition = 0
                        } else {
                            if (this.rooms[index][prop] === this.rooms[index - 1][prop]) {
                                this.roomSpanArr[idx][this.roomPosition] += 1// 有相同项
                                this.roomSpanArr[idx].push(0) // 名称相同后往数组里面加一项0
                            } else {
                                this.roomSpanArr[idx].push(1)// 同列的前后两行单元格不相同
                                this.roomPosition = index
                            }
                        }
                    })
                },
                roomObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex === 0 || columnIndex === 4) {
                        const _row = this.roomSpanArr[0][rowIndex]
                        const _col = _row > 0 ? 1 : 0
                        return {
                            rowspan: _row,
                            colspan: _col
                        }
                    }
                },
                objectSpanMethod({ row, column, rowIndex, columnIndex }) {
                    if (columnIndex === 0) {
                        const _row = this.spanArr[0][rowIndex]
                        const _col = _row > 0 ? 1 : 0
                        return {
                            rowspan: _row,
                            colspan: _col
                        }
                    }
                },
                
                // 踢下线
                async kickConnection(connection) {
                    this.$confirm(`确定要踢下线连接 "${connection.connId}" 吗？`, '确认踢下线', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            await axios.post(`/api/connections/${encodeURIComponent(connection.connId)}/kick`);
                            this.$message.success('已踢下线');
                            this.addLog(`已踢下线连接: ${connection.connId}`, 'warning');
                        } catch (error) {
                            this.$message.error('踢下线失败: ' + error.message);
                            this.addLog('踢下线失败: ' + error.message, 'error');
                        }
                    }).catch(() => {
                        this.$message.info('已取消踢下线');
                    });
                },
                
                // 发送广播消息
                async sendBroadcast() {
                    if (!this.broadcastForm.message.trim()) {
                        this.$message.warning('请输入消息内容');
                        return;
                    }
                    
                    this.broadcastLoading = true;
                    try {
                        // 发送真实广播消息
                        await axios.post('/api/message/broadcast', {
                            payload: {
                                cmd: 'cmd_admin_broadcast',
                                type: this.broadcastForm.type,
                                message: this.broadcastForm.message,
                                timestamp: Date.now()
                            }
                        });
                        this.$message.success('广播消息发送成功');
                        this.showBroadcastDialog = false;
                        this.broadcastForm.message = '';
                        this.addLog(`系统广播发送成功: ${this.broadcastForm.message}`, 'success');
                    } catch (error) {
                        this.$message.error('广播消息发送失败: ' + error.message);
                        this.addLog('广播消息发送失败: ' + error.message, 'error');
                    } finally {
                        this.broadcastLoading = false;
                    }
                },
                
                // 创建房间
                async createRoom() {
                    if (!this.roomForm.device_id.trim()) {
                        this.$message.warning('请输入设备ID');
                        return;
                    }
                    if (!this.roomForm.room_id.trim()) {
                        this.$message.warning('请输入房间ID');
                        return;
                    }
                    
                    this.roomLoading = true;
                    try {
                        // 创建真实房间（绑定设备）
                        const response = await axios.post('/api/device/bind', {
                            device_id: this.roomForm.device_id,
                            room_id: this.roomForm.room_id
                        });
                        this.$message.success('设备绑定成功');
                        this.showRoomDialog = false;
                        this.roomForm.device_id = '';
                        this.roomForm.room_id = '';
                        this.roomForm.maxParticipants = 10;
                        this.addLog(`设备绑定成功: ${response.data.roomId}`, 'success');
                    } catch (error) {
                        this.$message.error('设备绑定失败: ' + error.message);
                        this.addLog('设备绑定失败: ' + error.message, 'error');
                    } finally {
                        this.roomLoading = false;
                    }
                },
                
                // 查看房间
                async viewRoom(room) {
                    try {
                        const response = await axios.get(`/api/rooms/${room.id}`);
                        const details = response.data;
                        this.$alert(`
                            <div>
                                <p><strong>房间ID:</strong> ${details.id}</p>
                                <p><strong>成员数量:</strong> ${details.members.length}</p>
                                <p><strong>成员列表:</strong> ${details.members.join(', ') || '无'}</p>
                                <p><strong>通话成员:</strong> ${details.callMembers.join(', ') || '无'}</p>
                            </div>
                        `, '房间详情', {
                            dangerouslyUseHTMLString: true
                        });
                        this.addLog(`查看房间详情: ${room.name}`, 'info');
                    } catch (error) {
                        this.$message.error('获取房间详情失败: ' + error.message);
                        this.addLog('获取房间详情失败: ' + error.message, 'error');
                    }
                },
                
                // 结束房间通话
                async hangupRoom(room) {
                    this.$confirm(`确定要结束房间 "${room.name}" 的通话吗？`, '确认结束通话', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            await axios.post(`/api/rooms/${room.id}/hangup`);
                            this.$message.success('通话已结束');
                            this.addLog(`已结束房间通话: ${room.name}`, 'warning');
                        } catch (error) {
                            this.$message.error('结束通话失败: ' + error.message);
                            this.addLog('结束通话失败: ' + error.message, 'error');
                        }
                    }).catch(() => {
                        this.$message.info('已取消结束通话');
                    });
                },
                
                // 删除房间
                deleteRoom(room) {
                    this.$confirm(`确定要删除房间 "${room.name}" 吗？`, '确认删除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            await axios.delete(`/api/rooms/${room.id}`);
                            this.$message.success('房间删除成功');
                            this.addLog(`房间删除成功: ${room.name}`, 'success');
                        } catch (error) {
                            this.$message.error('房间删除失败: ' + error.message);
                            this.addLog('房间删除失败: ' + error.message, 'error');
                        }
                    }).catch(() => {
                        this.$message.info('已取消删除');
                    });
                },

                // 删除房间
                deleteDevice(device) {
                    this.$confirm(`确定要删除设备 "${device.deviceId}" 吗？`, '确认删除', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            await axios.delete(`/api/device/${device.roomId}/${device.deviceId}`)
                            this.$message.success('设备删除成功');
                            this.addLog(`设备删除成功: ${device.name}`, 'success');
                        } catch (error) {
                            this.$message.error('房间删除失败: ' + error.message);
                            this.addLog('设备删除失败: ' + error.message, 'error');
                        }
                    }).catch(() => {
                        this.$message.info('已取消删除');
                    });
                },
                
                // 清空所有房间
                clearAllRooms() {
                    this.$confirm('确定要清空所有房间吗？此操作不可恢复！', '确认清空', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        try {
                            const response = await axios.post('/api/rooms/cleanup-empty');
                            this.$message.success(`已清理 ${response.data.cleaned} 个空房间`);
                            this.addLog(`已清理 ${response.data.cleaned} 个空房间`, 'warning');
                        } catch (error) {
                            this.$message.error('清理房间失败: ' + error.message);
                            this.addLog('清理房间失败: ' + error.message, 'error');
                        }
                    }).catch(() => {
                        this.$message.info('已取消清空');
                    });
                },
                
                // 添加日志
                addLog(message, type = 'info') {
                    const timestamp = new Date().toLocaleTimeString();
                    this.logs.unshift({
                        timestamp,
                        message,
                        type
                    });
                    
                    // 限制日志数量
                    if (this.logs.length > 200) {
                        this.logs = this.logs.slice(0, 200);
                    }
                },
                
                // 清空日志
                clearLogs() {
                    this.logs = [];
                    this.addLog('日志已清空', 'info');
                }
            }
        });
    </script>
</body>
</html>
